package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sc.nft.dao.BoxItemDao;
import com.sc.nft.dao.BuyFirstCollectionDao;
import com.sc.nft.dao.BuyFirstUserDao;
import com.sc.nft.dao.DigitalCollectionDao;
import com.sc.nft.dao.DigitalCollectionProductInfoAuctionConditionDao;
import com.sc.nft.dao.DigitalCollectionProductInfoAuctionConsumptionConditionDao;
import com.sc.nft.dao.DigitalCollectionProductInfoAuctionDao;
import com.sc.nft.dao.DigitalCollectionProductInfoAuctionUserBiddingDao;
import com.sc.nft.dao.DigitalCollectionProductInfoConditionDao;
import com.sc.nft.dao.DigitalCollectionProductInfoDao;
import com.sc.nft.dao.DigitalCollectionProductInfoFreeSubscribeDao;
import com.sc.nft.dao.DigitalCollectionProductInfoSubscribeDao;
import com.sc.nft.dao.PrivilegeRuleDao;
import com.sc.nft.dao.ProductCdkDao;
import com.sc.nft.dao.ProductStockDao;
import com.sc.nft.dao.RushBuyCollectionDao;
import com.sc.nft.dao.RushBuyUserDao;
import com.sc.nft.dao.ShareProfitPanelDao;
import com.sc.nft.entity.AdminProductStockDetail;
import com.sc.nft.entity.BoxProduct;
import com.sc.nft.entity.CatenaInfo;
import com.sc.nft.entity.DigitalCollection;
import com.sc.nft.entity.DigitalCollectionProductInfo;
import com.sc.nft.entity.DigitalCollectionProductInfoAuction;
import com.sc.nft.entity.DigitalCollectionProductInfoAuctionCondition;
import com.sc.nft.entity.DigitalCollectionProductInfoAuctionConsumptionCondition;
import com.sc.nft.entity.DigitalCollectionProductInfoCondition;
import com.sc.nft.entity.DigitalCollectionProductInfoFreeSubscribe;
import com.sc.nft.entity.DigitalCollectionProductInfoSubscribe;
import com.sc.nft.entity.Privilege;
import com.sc.nft.entity.PrivilegeRule;
import com.sc.nft.entity.ProductCdk;
import com.sc.nft.entity.ProductStock;
import com.sc.nft.entity.ShareProfitPanel;
import com.sc.nft.entity.dto.AddAuctionProductDTO;
import com.sc.nft.entity.dto.AddSubscribeProductDTO;
import com.sc.nft.entity.dto.DigitalCollectionProductInfoAuctionConditionDTO;
import com.sc.nft.entity.dto.DigitalCollectionProductInfoAuctionDTO;
import com.sc.nft.entity.dto.ModificationSubscribeProductDTO;
import com.sc.nft.entity.dto.ModifyAuctionProductDTO;
import com.sc.nft.entity.vo.ALLCatenaVO;
import com.sc.nft.entity.vo.AirdropGrantproductVO;
import com.sc.nft.entity.vo.AssociateProductListByCommodityTypeVO;
import com.sc.nft.entity.vo.AuctionProductAdminVO;
import com.sc.nft.entity.vo.DigitalCollectionProductInfoConditioAdminVO;
import com.sc.nft.entity.vo.DigitalCollectionProductInfoFreeSubscribeAdminVO;
import com.sc.nft.entity.vo.HomePageDigitalCollectionProductVO;
import com.sc.nft.entity.vo.PageProductVO;
import com.sc.nft.entity.vo.ProductCdkVO;
import com.sc.nft.entity.vo.SubscribeProductAdminVO;
import com.sc.nft.enums.AcutionParticipationTypeEnum;
import com.sc.nft.enums.AppleProductEnum;
import com.sc.nft.enums.ClassifyType;
import com.sc.nft.enums.CollectionChainStatusEnum;
import com.sc.nft.enums.CommodityType;
import com.sc.nft.enums.StockType;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.AdminProductStockDetailService;
import com.sc.nft.service.BoxProductService;
import com.sc.nft.service.DigitalCollectionProductInfoService;
import com.sc.nft.service.PrivilegeService;
import com.sc.nft.sup.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * 服务接口实现
 *
 * @author rdg
 * @author Sun
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2022-05-30 15:19:18
 * /**
 * 服务接口实现
 * @since 2022-05-30 13:42:06
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DigitalCollectionProductInfoServiceImpl implements DigitalCollectionProductInfoService {
    private final DigitalCollectionProductInfoDao digitalCollectionProductInfoDao;
    private final BoxItemDao boxItemDao;
    private final ProductStockDao productStockDao;
    private final ProductCdkDao productCdkDao;
    private final DigitalCollectionDao digitalCollectionDao;
    private final PrivilegeRuleDao privilegeRuleDao;
    private final AdminProductStockDetailService adminProductStockDetailService;
    private final BuyFirstCollectionDao buyFirstCollectionDao;
    private final BuyFirstUserDao buyFirstUserDao;
    private final RushBuyUserDao rushBuyUserDao;
    private final RushBuyCollectionDao rushBuyCollectionDao;
    private final ShareProfitPanelDao shareProfitPanelDao;
    private final PrivilegeService privilegeService;
    private final BoxProductService boxProductService;
    private final DigitalCollectionProductInfoConditionDao digitalCollectionProductInfoConditionDao;
    private final DigitalCollectionProductInfoFreeSubscribeDao digitalCollectionProductInfoFreeSubscribeDao;
    private final DigitalCollectionProductInfoSubscribeDao digitalCollectionProductInfoSubscribeDao;

    private final DigitalCollectionProductInfoAuctionDao digitalCollectionProductInfoAuctionDao;

    private final DigitalCollectionProductInfoAuctionConditionDao digitalCollectionProductInfoAuctionConditionDao;

    private final DigitalCollectionProductInfoAuctionConsumptionConditionDao digitalCollectionProductInfoAuctionConsumptionConditionDao;
    private final DigitalCollectionProductInfoAuctionUserBiddingDao digitalCollectionProductInfoAuctionUserBiddingDao;


    @Override
    public List<HashMap> findAllBlindBox(int isIosShow) {
        List<HashMap> allBlindBox = digitalCollectionProductInfoDao.findAllBlindBox(isIosShow);
        for (HashMap blindBox : allBlindBox) {
            String beginTime = blindBox.get("beginTime").toString();
            if (ObjectUtil.isNotEmpty(beginTime)) {
                Date date = DateUtil.parse(beginTime, "yyyy-MM-dd HH:mm:ss");
                blindBox.put("beginTime", DateUtil.format(date, "MM-dd HH:mm"));
            }
        }
        return allBlindBox;
    }

    @Override
    public List<ALLCatenaVO> findBlindBoxCatena(int isIosShow) {
        return digitalCollectionProductInfoDao.findBlindBoxCatena(isIosShow);
    }

    @Override
    public List<HomePageDigitalCollectionProductVO> getTop10DigitalCollection(int isIosShow) {
        return digitalCollectionProductInfoDao.getTop10DigitalCollection(isIosShow);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProduct(DigitalCollectionProductInfo productInfo, ProductStock productStock) {
        productInfo.insert();
        if (productInfo.getTypeClassify() == ClassifyType.COLLECTION) {
            digitalCollectionDao.uodateCollectionStock(productInfo.getRelationId(), productStock.getSumCount());
        }
        productStock.setProductId(productInfo.getId());
        productStock.insert();
        if (productInfo.getTypeClassify() == ClassifyType.BLIND_BOX) {
            boxItemDao.getBoxItem(productInfo.getRelationId()).forEach(boxItem -> {
                ProductStock productStockItem = new ProductStock();
                DigitalCollection digitalCollection = digitalCollectionDao.getById(boxItem.getCollectionId());
                if (digitalCollection.getUsableCount() < boxItem.getSumCount()) {
                    throw new GlobalRunTimeException("盲盒中的" + digitalCollection.getFirstTitle() + "库存不足");
                }
                digitalCollectionDao.uodateCollectionStock(digitalCollection.getId(), boxItem.getSumCount());
                productStockItem.setStockType(StockType.BOX_ITEM);
                productStockItem.setVersion(0);
                productStockItem.setProductId(productInfo.getId());
                productStockItem.setRelationId(productInfo.getRelationId());
                productStockItem.setStockType(StockType.BOX_ITEM);
                productStockItem.setItemId(boxItem.getId());
                productStockItem.setSumCount(boxItem.getSumCount());
                productStockItem.setUsableCount(boxItem.getSumCount());
                productStockItem.setFrozenCount(0);
                productStockItem.setSellCount(0);
                productStockItem.insert();
            });
        }

    }

    @Override
    public Page<PageProductVO> pageProduct(String firstTitle, String productUuid, Boolean status, Boolean isSoldOut, Integer commodityType, Integer classifyType, int pageNo, int pageSize) {
        Page<PageProductVO> pageProductVOPage = digitalCollectionProductInfoDao.pageProduct(firstTitle, productUuid, status, isSoldOut, commodityType, classifyType, pageNo, pageSize);
        List<PageProductVO> records = pageProductVOPage.getRecords();
        for (PageProductVO record : records) {
            record.setCommodityTypeName(record.getCommodityType().getDescription());
            //当前时间在抢购结束时间之前 并且  是普通商品才可以一键售罄
            record.setIsCanSoldOut(CommodityType.PRODUCT == record.getCommodityType() && DateUtil.date().isBefore(ObjectUtil.isNull(record.getEndTime()) ? DateUtil.date() : record.getEndTime()));
        }
        return pageProductVOPage;
    }

    @Override
    public void updateProductStatus(Long id, Boolean status, Boolean isEnable) {
        DigitalCollectionProductInfo byId = digitalCollectionProductInfoDao.getById(id);
        //售罄后就无法开启购买
        if (byId.getIsSoldOut() && ObjectUtil.isNotEmpty(isEnable) && isEnable) {
            throw new GlobalRunTimeException("售罄的商品无法开启购买");
        }
        if (ObjectUtil.isNotEmpty(status) && status) {
            if ((byId.getCommodityType().equals(CommodityType.SYNTHESIS) || byId.getCommodityType().equals(CommodityType.PRIVILEGE))) {
                List<PrivilegeRule> list = privilegeRuleDao.getRuleByProductId(byId.getId());
                if (list.size() <= 0) {
                    throw new GlobalRunTimeException("合成商品,特权商品设置合成条件后才能上架");
                }
            }

            //普通商品
            if (byId.getCommodityType() == CommodityType.PRODUCT) {
                //优先购
                if (byId.getIsPriorityPurchase()) {
                    //如果设置了优先购 则需要判断是否设置白名单或者藏品
                    HashSet<Boolean> buyFirsSet = Sets.newHashSet();


                    buyFirsSet.add(buyFirstCollectionDao.getIsExistByProductId(byId.getId()));
                    buyFirsSet.add(buyFirstUserDao.getIsExistByProductId(byId.getId()));

                    //如果两个都没有设置 则不允许上架
                    if (!buyFirsSet.contains(Boolean.TRUE)) {
                        throw new GlobalRunTimeException("优先购未设置白名单或者藏品");
                    }
                }
                //优先抢
                if (byId.getIsRushBuy()) {
                    //如果设置了优先抢 则需要判断是否设置白名单或者藏品
                    HashSet<Boolean> rushBuySet = Sets.newHashSet();
                    rushBuySet.add(rushBuyCollectionDao.getIsExistByProductId(byId.getId()));
                    rushBuySet.add(rushBuyUserDao.getIsExistByProductId(byId.getId()));

                    //如果两个都没有设置 则不允许上架
                    if (!rushBuySet.contains(Boolean.TRUE)) {
                        throw new GlobalRunTimeException("优先抢未设置白名单或者藏品");
                    }
                }


            }


        }
        if (ObjectUtil.isNotEmpty(isEnable) && isEnable) {
            if (DateTime.now().isBefore(byId.getBeginTime()) || DateTime.now().isAfter(byId.getEndTime())) {
                throw new GlobalRunTimeException("商品未到开始时间或者商品结束时间已过");
            }
            ProductStock productStock = productStockDao.getProductStock(id, byId.getRelationId(), null);
            if (productStock.getUsableCount() <= 0) {
                throw new GlobalRunTimeException(ErrorCode.COUNT_NOT_ENOUGH);
            }
            if (byId.getCommodityType() == CommodityType.PRODUCT && ObjectUtil.isEmpty(byId.getBeginTime())) {
                throw new GlobalRunTimeException(ErrorCode.BEGIN_TIME_NOT_SET);
            }
        }
        digitalCollectionProductInfoDao.updateProductStatus(id, status, isEnable);
    }

    @Override
    public List<DigitalCollectionProductInfo> inviteTaskProductList() {
        return digitalCollectionProductInfoDao.inviteTaskProductList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateConcernedNumRequest(Long id, Long concernedNum) {
        DigitalCollectionProductInfo digitalCollectionProductInfo = new DigitalCollectionProductInfo();
        digitalCollectionProductInfo.setCollectionsConcernedNum(concernedNum);
        digitalCollectionProductInfo.setId(id);
        digitalCollectionProductInfo.updateById();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStock(Long id, Boolean isAdd, Integer number) {
        DigitalCollectionProductInfo collectionProductInfo = digitalCollectionProductInfoDao.getById(id);
        DateTime now = DateUtil.date();
//        //优先购
//        if (collectionProductInfo.getIsPriorityPurchase() && now.getTime() >= collectionProductInfo.getPriorityPurchaseBeginTime().getTime()
//                && now.getTime() <= collectionProductInfo.getPriorityPurchaseEndTime().getTime()){
//            throw new GlobalRunTimeException("优先购时间内不允许修改库存");
//        }
//        //优先抢
//        if (collectionProductInfo.getIsRushBuy() && now.getTime() >= collectionProductInfo.getRushBuyBeginTime().getTime()
//                && now.getTime() <= collectionProductInfo.getRushBuyEndTime().getTime()){
//            throw new GlobalRunTimeException("优先抢时间内不允许修改库存");
//        }
//        //正常售卖
//        if (now.getTime() >= collectionProductInfo.getBeginTime().getTime() && now.getTime() <=collectionProductInfo.getEndTime().getTime()){
//            throw new GlobalRunTimeException("在抢购时间内不允许修改库存");
//        }
        if (collectionProductInfo.getStatus()) {
            throw new GlobalRunTimeException("上架中不允许修改库存！");
        }
        if (ObjectUtil.isEmpty(collectionProductInfo)) {
            throw new GlobalRunTimeException("不存在此商品！");
        }
        if (ClassifyType.BLIND_BOX == collectionProductInfo.getTypeClassify()) {
            throw new GlobalRunTimeException("盲盒类型不能修改库存！");
        }
        if (CommodityType.CDK_PRODUCT == collectionProductInfo.getCommodityType()) {
            throw new GlobalRunTimeException("CDK商品不能修改库存！");
        }
        if (CommodityType.SUBSCRIBE_COMMODITY == collectionProductInfo.getCommodityType()) {
            throw new GlobalRunTimeException("申购商品不能修改库存！");
        }
        ProductStock productStock = productStockDao.getByProductId(collectionProductInfo.getId());
        if (productStock.getFrozenCount() > 0) {
            throw new GlobalRunTimeException("仍有订单未释放可用库存");
        }
        Integer usableStockCount = productStock.getUsableCount();
        AdminProductStockDetail adminProductStockDetail = new AdminProductStockDetail();
        if (isAdd) {
            DigitalCollection digitalCollection = digitalCollectionDao.getById(collectionProductInfo.getRelationId());
            if (number > digitalCollection.getUsableCount()) {
                throw new GlobalRunTimeException("当前藏品可用库存不足！");
            }
            //增加商品可用库存数量
            Integer addRow = productStockDao.updateUsableCount(id, digitalCollection.getId(), Boolean.TRUE, number);

            //减少藏品可用库存数量
            Integer subRow = digitalCollectionDao.subUsableStock(digitalCollection.getId(), number);
            //只允许修改一条数据，如果有一个更新1条一个更新0条，则报错回滚，不允许藏品和商品库存更新不一致
            if (addRow != 1 || subRow != 1) {
                throw new GlobalRunTimeException("修改库存出错");
            }
            adminProductStockDetail.setAfterNumber(usableStockCount + number);
//            //如果商品可用数量超过商品总库存则扩大总库存
//            if (usableStockCount + number > productStock.getSumCount()){
//                productStockDao.overSizeSumCount(id,digitalCollection.getId(),usableStockCount + number);
//            }

        } else {
            if (number > usableStockCount) {
                throw new GlobalRunTimeException("可出售数量小于减少数量！");
            }
            //减少商品可用库存数量
            Integer subRow = productStockDao.subUsableCount(id, collectionProductInfo.getRelationId(), number);
            //增加藏品可用库存数量
            Integer addRow = digitalCollectionDao.updateUsableStock(collectionProductInfo.getRelationId(), Boolean.TRUE, number);
            //只允许修改一条数据，如果有一个更新1条一个更新0条，则报错回滚，不允许藏品和商品库存更新不一致
            if (addRow != 1 || subRow != 1) {
                throw new GlobalRunTimeException("修改库存出错");
            }
            adminProductStockDetail.setAfterNumber(usableStockCount - number);
        }
        //新增库存调整记录
        adminProductStockDetail.setNumber(number);
        adminProductStockDetail.setProductId(id);
        adminProductStockDetail.setIsAdd(isAdd);
        adminProductStockDetail.setBeforeNumber(usableStockCount);
        adminProductStockDetail.setFirstTitle(collectionProductInfo.getFirstTitle());
        adminProductStockDetailService.add(adminProductStockDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void soldOut(Long id) {
        DigitalCollectionProductInfo collectionProductInfo = digitalCollectionProductInfoDao.getById(id);
        if (CommodityType.PRODUCT != collectionProductInfo.getCommodityType()) {
            throw new GlobalRunTimeException("非普通商品不支持一键售罄！");
        }
        DateTime now = DateUtil.date();
        //优先购
        if (collectionProductInfo.getIsPriorityPurchase() && now.getTime() <= collectionProductInfo.getPriorityPurchaseBeginTime().getTime()) {
            throw new GlobalRunTimeException("优先购还未开始，无法一键售罄");
        }
        //优先抢
        else if (collectionProductInfo.getIsRushBuy() && now.getTime() <= collectionProductInfo.getRushBuyBeginTime().getTime()) {
            throw new GlobalRunTimeException("优先抢还未开始，无法一键售罄");
        } else if (now.getTime() <= collectionProductInfo.getBeginTime().getTime()
                && now.getTime() >= collectionProductInfo.getEndTime().getTime()) {
            throw new GlobalRunTimeException("不在售卖时间内，无法一键售罄");
        }
        digitalCollectionProductInfoDao.soldOut(id);
    }

    @Override
    public Page<AirdropGrantproductVO> airdropGrantProduct(Page page, String firstTitle, String productUuid, Integer typeClassify, Integer commodityType) {
        return digitalCollectionProductInfoDao.airdropGrantProduct(page, firstTitle, productUuid, typeClassify, commodityType);
    }

    @Override
    public void autoOpenProductBegin(DigitalCollectionProductInfo digitalCollectionProductInfo) {
        //获取该商品的库存
        ProductStock productStock = productStockDao.getProductStock(digitalCollectionProductInfo.getId(), digitalCollectionProductInfo.getRelationId(), null);
        //可用库存大于零才开启
        if (productStock.getUsableCount() > 0) {
            //校验当前时间在商品开启时间之后,在商品结束时间之前
            if (DateTime.now().isAfter(digitalCollectionProductInfo.getBeginTime()) && DateTime.now().isBefore(digitalCollectionProductInfo.getEndTime())) {
                digitalCollectionProductInfoDao.openProductBegin(digitalCollectionProductInfo.getId());
            }
        }
    }


    @Override
    public void closeProductEnd() {
        //查询所有productType=1 (开启中) status=1(上架中) is_back_stock=0 没有归还库存 的商品
        List<DigitalCollectionProductInfo> list = digitalCollectionProductInfoDao.getAllNoEndProduct();
        for (DigitalCollectionProductInfo product : list) {
            //获取该商品的库存
            ProductStock productStock = productStockDao.getProductStock(product.getId(), product.getRelationId(), null);
            //当(商品结束时间不为空且当前时间在结束时间之后)或者(结束时间为空 可用库存为零)
            if (ObjectUtil.isNotEmpty(product.getEndTime())) {
                if (DateTime.now().isAfter(product.getEndTime())) {
                    Boolean aBoolean = digitalCollectionProductInfoDao.closeProductEnd(product.getId());
                }
            } else {
                if (productStock.getUsableCount() <= 0) {
                    Boolean aBoolean = digitalCollectionProductInfoDao.closeProductEnd(product.getId());
                }
            }


        }
    }

    @Override
    public Page<AssociateProductListByCommodityTypeVO> getAssociateProductListByCommodityType(CommodityType commodityType, Integer pageNo, Integer pageSize, String firstTitle, ClassifyType typeClassify) {
        return digitalCollectionProductInfoDao.getAssociateProductListByCommodityType(new Page<>(pageNo, pageSize), commodityType, firstTitle, typeClassify);
    }

    @Override
    public Page<AssociateProductListByCommodityTypeVO> getAllAssociateProductListByCommodityType(CommodityType commodityType, Integer pageNo, Integer pageSize, String firstTitle, ClassifyType typeClassify) {
        return digitalCollectionProductInfoDao.getAllAssociateProductListByCommodityType(new Page<>(pageNo, pageSize), commodityType, firstTitle, typeClassify);
    }


    /**
     * 获取芯片商品
     *
     * @param pageNo
     * @param pageSize
     * @param firstTitle
     * @return
     */
    @Override
    public Page<AssociateProductListByCommodityTypeVO> getAssociateChipProductList(Integer pageNo, Integer pageSize, String firstTitle) {
        return digitalCollectionProductInfoDao.getAssociateChipProductList(new Page<>(pageNo, pageSize), firstTitle);

    }

    /**
     * 这个功能是创建商品功能的一个延伸功能,创建申购商品,区别在于申购逻辑比较复杂.所以需要单独引出来一个.
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSubscribeProduct(AddSubscribeProductDTO request) {
        if (request.getCommodityType() != CommodityType.SUBSCRIBE_COMMODITY) {
            throw new GlobalRunTimeException("该类型无法创建商品");
        }
        if (request.getIsSmeltingOnly() != null && request.getIsSmeltingOnly()) {
            if (request.getIsLockedPosition()) {
                throw new GlobalRunTimeException("锁仓和仅熔炼无法同时配置");
            }
            if (request.getCommodityType() != CommodityType.SUBSCRIBE_COMMODITY) {
                throw new GlobalRunTimeException("仅普通商品和空投商品新增是否仅熔炼配置");
            }
        }
        // 锁仓判定
        if (!request.lockedPositionDecide()) {
            throw new GlobalRunTimeException(ErrorCode.LOCKED_POSITION);
        }
        // subscribeStartTime申购开始时间 subscribeEndTime申购结束时间 consistenceStartTime 抽签开始时间 consistenceEndTime结果公布时间 beginTime开始时间 endTime结束时间
        // 申购开始时间<申购结束时间<抽签开始时间<结果公布时间<开始购买时间<活动结束时间,每一组时间进行判定.给独立的异常抛出描述
        if (request.getSubscribeStartTime().after(request.getSubscribeEndTime())) {
            throw new GlobalRunTimeException("申购开始时间不能在结束时间之后");
        }
        if (request.getSubscribeEndTime().after(request.getConsistenceStartTime())) {
            throw new GlobalRunTimeException("申购结束时间不能在抽签开始时间之后");
        }
        if (request.getConsistenceStartTime().after(request.getConsistenceEndTime())) {
            throw new GlobalRunTimeException("抽签开始时间不能在结果公布时间之后");
        }
        if (request.getConsistenceEndTime().after(request.getBeginTime())) {
            throw new GlobalRunTimeException("结果公布时间不能在开始购买时间之后");
        }
        if (request.getBeginTime().after(request.getEndTime())) {
            throw new GlobalRunTimeException("开始购买时间不能在活动结束时间之后");
        }
        if (request.getTypeClassify() == ClassifyType.COLLECTION) {
            if (request.getProductCount() < request.getMaxSubscribe()) {
                throw new GlobalRunTimeException("中签数量不可以大于商品数");
            }
        }
        DigitalCollectionProductInfo productInfo = BeanUtil.toBean(request, DigitalCollectionProductInfo.class);
        ProductStock productStock = new ProductStock();
        productInfo.setStatus(false);
        productInfo.setIsEnable(false);
        productInfo.setIsSoldOut(false);
        productInfo.setIsRegisterTime(Boolean.FALSE);
        productInfo.setIsPriorityPurchase(Boolean.FALSE);//优先购
        productInfo.setIsRushBuy(Boolean.FALSE);//优先抢
        productInfo.setIsUpgrade(Boolean.FALSE);//升级藏品
        productInfo.setAppleProductId(AppleProductEnum.SEVENTY_THREE.getId());
//        if (request.getCommodityType() == CommodityType.PRODUCT && request.getIsRegisterTime()) {
//            if (ObjectUtil.isNull(request.getRegisterEndTime()) || ObjectUtil.isNull(request.getRegisterBeginTime())) {
//                throw new GlobalRunTimeException("注册限制时间不能为空");
//            }
//
//            if (request.getRegisterBeginTime().after(request.getRegisterEndTime())) {
//                throw new GlobalRunTimeException("注册开始时间不能在结束时间之后");
//            }
//
        productInfo.setIsRegisterTime(Boolean.FALSE);
//            productInfo.setRegisterBeginTime(request.getRegisterBeginTime());
//            productInfo.setRegisterEndTime(request.getRegisterEndTime());
//        }

        if (request.getCommodityType() == CommodityType.SUBSCRIBE_COMMODITY) {
            if (ObjectUtil.isNull(request.getShareProfitPanelId())) {
                throw new GlobalRunTimeException("分润模板不能为空");
            }
            ShareProfitPanel panel = shareProfitPanelDao.getById(request.getShareProfitPanelId());
            if (ObjectUtil.isNull(panel)) {
                throw new GlobalRunTimeException("请选择分润模板");
            }
            productInfo.setShareProfitPanelId(panel.getId());
        }

        CatenaInfo catenaInfo = (CatenaInfo) new CatenaInfo().selectById(productInfo.getCatenaId());
        if (ObjectUtil.isNotEmpty(catenaInfo)) {
            productInfo.setCatenaName(catenaInfo.getName());
        }

        long snowflakeNextId = IdUtil.getSnowflakeNextId();
        productInfo.setDigitalCollectionProductInfoUuid("nft" + String.valueOf(snowflakeNextId));
        if (request.getEquityPropsId() != 0 && request.getVoucherSum() == 0) {
            throw new GlobalRunTimeException("权益商品数量不能为0");
        }

        switch (request.getTypeClassify()) {

            case COLLECTION:
                DigitalCollection digitalCollection = digitalCollectionDao.getById(productInfo.getRelationId());
                if (digitalCollection.getChainStatus() != CollectionChainStatusEnum.CHAIN_COMPLETED) {
                    throw new GlobalRunTimeException("该藏品未上链，不能创建商品");
                }
                if (request.getTypeClassify() == ClassifyType.COLLECTION) {
                    if (request.getProductCount() <= 0) {
                        throw new GlobalRunTimeException("商品数量不正确");
                    }
                }
                if (productInfo.getTypeClassify() == ClassifyType.COLLECTION) {
                    if (request.getProductCount() > digitalCollection.getUsableCount()) {
                        throw new GlobalRunTimeException("藏品库存不足");
                    }
                }
                //特权藏品校验是否设置权益
                if (digitalCollection.getIsPrivilege()) {
                    List<Privilege> list = privilegeService.getByCollectionId(digitalCollection.getId());
                    if (list.size() <= 0) {
                        throw new GlobalRunTimeException("特权藏品未设置权益");
                    }
                }
                productInfo.setIsUpgrade(digitalCollection.getIsUpgrade());
                productInfo.setDaoLevel(digitalCollection.getDaoLevel());
                productInfo.setUserCreatorId(digitalCollection.getUserCreatorId());
                productInfo.setLevel(digitalCollection.getLevel().getCode());
                productInfo.setIsUpgrade(digitalCollection.getIsUpgrade());
                productInfo.setDaoLevel(digitalCollection.getDaoLevel());
                productInfo.setModelImg(digitalCollection.getModelImg());
                productInfo.setModelDistance(digitalCollection.getModelDistance());
                productStock.setSellCount(0);
                productStock.setFrozenCount(0);
                productStock.setUsableCount(request.getProductCount());
                productStock.setSumCount(request.getProductCount());
                productStock.setStockType(StockType.COLLECTION);
                productStock.setRelationId(request.getRelationId());
                productInfo.setThreeModelId(digitalCollection.getThreeModelId());
                productInfo.setSkipUrl(digitalCollection.getSkipUrl());
                productStock.setVersion(0);
                break;
            case BLIND_BOX:
                BoxProduct boxProduct = boxProductService.getById(request.getRelationId());
                productInfo.setUserCreatorId(boxProduct.getUserCreatorId());
                productInfo.setAboutBox(boxProduct.getAboutBox());
                productInfo.setBoxDetailsPicture(boxProduct.getBoxDetailsPicture());
                productInfo.setProductPresentation(boxProduct.getProductPresentation());
                if (productInfo.getCommodityType() == CommodityType.PRODUCT) {
                    productInfo.setAppleProductId(AppleProductEnum.BLINDBOX.getId());
                }
                if (BooleanUtil.isFalse(boxProduct.getStatus())) {
                    throw new GlobalRunTimeException("盲盒未上架");
                }
                productStock.setStockType(StockType.BLIND_BOX);
                productStock.setSellCount(0);
                productStock.setFrozenCount(0);
                productStock.setUsableCount(boxProduct.getBoxCount());
                productStock.setRelationId(request.getRelationId());
                productStock.setSumCount(boxProduct.getBoxCount());
                productStock.setVersion(0);
                break;
        }

        productInfo.setEquityPropsNum(request.getVoucherSum());
        productInfo.insert();
        if (productInfo.getTypeClassify() == ClassifyType.COLLECTION) {
            digitalCollectionDao.uodateCollectionStock(productInfo.getRelationId(), productStock.getSumCount());
        }
        productStock.setProductId(productInfo.getId());
        productStock.insert();
        if (productInfo.getTypeClassify() == ClassifyType.BLIND_BOX) {
            boxItemDao.getBoxItem(productInfo.getRelationId()).forEach(boxItem -> {
                ProductStock productStockItem = new ProductStock();
                DigitalCollection boxDigital = digitalCollectionDao.getById(boxItem.getCollectionId());
                if (boxDigital.getUsableCount() < boxItem.getSumCount()) {
                    throw new GlobalRunTimeException("盲盒中的" + boxDigital.getFirstTitle() + "库存不足");
                }
                digitalCollectionDao.uodateCollectionStock(boxDigital.getId(), boxItem.getSumCount());
                productStockItem.setStockType(StockType.BOX_ITEM);
                productStockItem.setVersion(0);
                productStockItem.setProductId(productInfo.getId());
                productStockItem.setRelationId(productInfo.getRelationId());
                productStockItem.setStockType(StockType.BOX_ITEM);
                productStockItem.setItemId(boxItem.getId());
                productStockItem.setSumCount(boxItem.getSumCount());
                productStockItem.setUsableCount(boxItem.getSumCount());
                productStockItem.setFrozenCount(0);
                productStockItem.setSellCount(0);
                productStockItem.insert();
            });
        }

        // 触发钩子,组装
        request.trigger(productInfo.getId());

        // 新增对应的数据
        DigitalCollectionProductInfoSubscribe digitalCollectionProductInfoSubscribe = request.getDigitalCollectionProductInfoSubscribe();
        digitalCollectionProductInfoSubscribeDao.save(digitalCollectionProductInfoSubscribe);
        List<DigitalCollectionProductInfoCondition> digitalCollectionProductInfoConditions = request.getDigitalCollectionProductInfoConditions();
        digitalCollectionProductInfoConditionDao.saveBatch(digitalCollectionProductInfoConditions);
        List<DigitalCollectionProductInfoFreeSubscribe> digitalCollectionProductInfoFreeSubscribes = request.getDigitalCollectionProductInfoFreeSubscribes();
        digitalCollectionProductInfoFreeSubscribeDao.saveBatch(digitalCollectionProductInfoFreeSubscribes);
    }

    @Override
    public SubscribeProductAdminVO getSubscribeProductById(Long id) {
        DigitalCollectionProductInfo digitalCollectionProductInfo = (DigitalCollectionProductInfo) new DigitalCollectionProductInfo().selectById(id);
        SubscribeProductAdminVO subscribeProductAdminVO = BeanUtil.toBean(digitalCollectionProductInfo, SubscribeProductAdminVO.class);
        subscribeProductAdminVO.setTypeClassify(digitalCollectionProductInfo.getTypeClassify());
        ShareProfitPanel panel = shareProfitPanelDao.getById(digitalCollectionProductInfo.getShareProfitPanelId());
        if (ObjectUtil.isNotEmpty(panel)) {
            subscribeProductAdminVO.setShareProfitPanelId(panel.getId());
            subscribeProductAdminVO.setShareProfitPanelName(panel.getPanelName());
        }
        // 根据判定获取时间判断.
        DigitalCollectionProductInfoSubscribe digitalCollectionProductInfoSubscribe = digitalCollectionProductInfoSubscribeDao.getByProductInfoSubscribe(id);
        if (BeanUtil.isEmpty(digitalCollectionProductInfoSubscribe)) {
            throw new GlobalRunTimeException("该任务数据异常,请联系管理人员");
        }
        // 数据拷贝进去
        BeanUtil.copyProperties(digitalCollectionProductInfoSubscribe, subscribeProductAdminVO);
        if (digitalCollectionProductInfoSubscribe.getParticipationCondition()) {
            // 有条件参与条件要求,把参与条件写进去.
            List<DigitalCollectionProductInfoCondition> conditionsData = digitalCollectionProductInfoConditionDao.getDigitalCollectionProductInfoConditionBatchByProductId(id);
            subscribeProductAdminVO.setAddCondition(CollUtil.isNotEmpty(conditionsData) ? BeanUtil.copyToList(conditionsData, DigitalCollectionProductInfoConditioAdminVO.class) : Lists.newArrayList());
        }
        if (digitalCollectionProductInfoSubscribe.getFreeSubscribe()) {
            // 有免费的申购码配置.把申购码配置写进去.
            List<DigitalCollectionProductInfoFreeSubscribe> digitalCollectionProductInfoFreeSubscribeAdmin = digitalCollectionProductInfoFreeSubscribeDao.getDigitalCollectionProductInfoFreeSubscribeAdmin(id);
            subscribeProductAdminVO.setAddFreeSubscribes(CollUtil.isNotEmpty(digitalCollectionProductInfoFreeSubscribeAdmin) ? BeanUtil.copyToList(digitalCollectionProductInfoFreeSubscribeAdmin, DigitalCollectionProductInfoFreeSubscribeAdminVO.class) : Lists.newArrayList());
        }
        return subscribeProductAdminVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modificationSubscribeProduct(ModificationSubscribeProductDTO request) {
        DigitalCollectionProductInfo digitalCollectionProductInfo = (DigitalCollectionProductInfo) new DigitalCollectionProductInfo().selectById(request.getProductId());
        if (ObjectUtil.isEmpty(digitalCollectionProductInfo)) {
            throw new GlobalRunTimeException(ErrorCode.PRODUCT_NOT_FOUND);
        }

        if (!digitalCollectionProductInfo.getIsSmeltingOnly().equals(request.getIsSmeltingOnly())) {
            throw new GlobalRunTimeException("仅熔炼选项不支持修改");
        }

        if (digitalCollectionProductInfo.getStatus()) {
            throw new GlobalRunTimeException("商品上架中不可做修改");
        }
        if (ObjectUtil.isNull(request.getShareProfitPanelId())) {
            throw new GlobalRunTimeException("请选择分润模板");
        }
        ShareProfitPanel panel = shareProfitPanelDao.getById(request.getShareProfitPanelId());
        if (ObjectUtil.isNull(panel)) {
            throw new GlobalRunTimeException("未找到分润模板");
        }

        //设置注册开始时间和结束时间
//        if(request.getIsRegisterTime()){
//            if(ObjectUtil.isNull(request.getRegisterEndTime()) || ObjectUtil.isNull(request.getRegisterBeginTime())){
//                throw new GlobalRunTimeException("注册限制时间不能为空");
//            }
//
//
//            if(request.getRegisterBeginTime().after(request.getRegisterEndTime())){
//                throw new GlobalRunTimeException("注册开始时间不能在结束时间之后");
//            }
//
        digitalCollectionProductInfo.setIsRegisterTime(Boolean.FALSE);
//            digitalCollectionProductInfo.setRegisterBeginTime(request.getRegisterBeginTime());
//            digitalCollectionProductInfo.setRegisterEndTime(request.getRegisterEndTime());
//        }

        digitalCollectionProductInfo.setShareProfitPanelId(panel.getId());


        if (digitalCollectionProductInfo.getEndTime() != request.getEndTime() && DateTime.now().isAfter(digitalCollectionProductInfo.getEndTime())) {
            throw new GlobalRunTimeException("商品已过期，不能修改");
        }
        // subscribeStartTime申购开始时间 subscribeEndTime申购结束时间 consistenceStartTime 抽签开始时间 consistenceEndTime结果公布时间 beginTime开始时间 endTime结束时间
        // 申购开始时间<申购结束时间<抽签开始时间<结果公布时间<开始购买时间<活动结束时间,每一组时间进行判定.给独立的异常抛出描述
        if (request.getSubscribeStartTime().after(request.getSubscribeEndTime())) {
            throw new GlobalRunTimeException("申购开始时间不能在结束时间之后");
        }
        if (request.getSubscribeEndTime().after(request.getConsistenceStartTime())) {
            throw new GlobalRunTimeException("申购结束时间不能在抽签开始时间之后");
        }
        if (request.getConsistenceStartTime().after(request.getConsistenceEndTime())) {
            throw new GlobalRunTimeException("抽签开始时间不能在结果公布时间之后");
        }
        if (request.getConsistenceEndTime().after(request.getBeginTime())) {
            throw new GlobalRunTimeException("结果公布时间不能在开始购买时间之后");
        }
        if (request.getBeginTime().after(request.getEndTime())) {
            throw new GlobalRunTimeException("开始购买时间不能在活动结束时间之后");
        }
        // 中签数量不可以小于商品数
        if (digitalCollectionProductInfo.getTypeClassify() == ClassifyType.COLLECTION) {
            if (request.getMaxSubscribe() > request.getProductCount()) {
                throw new GlobalRunTimeException("中签数量不可以大于商品数");
            }
        }

        if (request.getEquityPropsId() != 0 && request.getVoucherSum() == 0) {
            throw new GlobalRunTimeException("权益商品数量不能为0");
        }
        digitalCollectionProductInfo.setEquityPropsId(request.getEquityPropsId());
        digitalCollectionProductInfo.setEquityPropsNum(request.getVoucherSum());
        digitalCollectionProductInfo.setCollectionsConcernedNum(request.getCollectionsConcernedNum());

        digitalCollectionProductInfo.setFirstTitle(request.getFirstTitle());
//        digitalCollectionProductInfo.setProductType(request.getProductType());
        digitalCollectionProductInfo.setProductNum(request.getProductNum());
        digitalCollectionProductInfo.setIntegralNum(request.getIntegralNum());
        digitalCollectionProductInfo.setBeginTime(request.getBeginTime());
        digitalCollectionProductInfo.setEndTime(request.getEndTime());
        digitalCollectionProductInfo.setUpperLimit(request.getUpperLimit());
        digitalCollectionProductInfo.setPlatformShow(request.getPlatformShow());
        digitalCollectionProductInfo.setBrandShow(request.getBrandShow());
        digitalCollectionProductInfo.setFirmShow(request.getFirmShow());
        digitalCollectionProductInfo.setEquityPropsNum(request.getVoucherSum());
        digitalCollectionProductInfo.updateById();

        // 触发钩子,组装
        request.trigger(request.getProductId());

        // 修改数据详情配置.
        DigitalCollectionProductInfoSubscribe byProductInfoSubscribe = digitalCollectionProductInfoSubscribeDao.getByProductInfoSubscribe(request.getProductId());
        if (BeanUtil.isNotEmpty(byProductInfoSubscribe)) {
            BeanUtil.copyProperties(request.getDigitalCollectionProductInfoSubscribe(), byProductInfoSubscribe);
        }
        digitalCollectionProductInfoSubscribeDao.updateByProductId(byProductInfoSubscribe);
        // 干掉对应的免费申购码的申请条件以及持仓条件申购数据,在重新写入
        digitalCollectionProductInfoConditionDao.removeByProductId(request.getProductId());
        digitalCollectionProductInfoFreeSubscribeDao.removeByProductId(request.getProductId());


        // 新增对应的数据
        List<DigitalCollectionProductInfoCondition> digitalCollectionProductInfoConditions = request.getDigitalCollectionProductInfoConditions();
        digitalCollectionProductInfoConditionDao.saveBatch(digitalCollectionProductInfoConditions);
        List<DigitalCollectionProductInfoFreeSubscribe> digitalCollectionProductInfoFreeSubscribes = request.getDigitalCollectionProductInfoFreeSubscribes();
        digitalCollectionProductInfoFreeSubscribeDao.saveBatch(digitalCollectionProductInfoFreeSubscribes);
    }


    @Override
    public List<DigitalCollectionProductInfo> getByCollectionId(Long collectionId) {
        return digitalCollectionProductInfoDao.getByCollectionId(collectionId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateCDK(Long productId) {
        DigitalCollectionProductInfo productInfo = digitalCollectionProductInfoDao.getOneByProductIdAndCommodityType(productId, CommodityType.CDK_PRODUCT);
        if (ObjectUtil.isEmpty(productInfo)) {
            throw new GlobalRunTimeException(ErrorCode.PARAM_ERROR);
        }

        Integer usableStockCount = productStockDao.getUsableStockCount(productId);
        if (ObjectUtil.isEmpty(usableStockCount)) {
            throw new GlobalRunTimeException(ErrorCode.PARAM_ERROR);
        }

        List<ProductCdk> list = productCdkDao.getOneByProductId(productInfo);
        if (list.size() > 0) {
            throw new GlobalRunTimeException(ErrorCode.CDK_HAS_BEEN_GENERATER);
        }
        HashSet<String> cdks = generateCDK(usableStockCount);

        for (String cdk : cdks) {
            ProductCdk productCdk = new ProductCdk();
            productCdk.setProductId(productId);
            productCdk.setIsUse(Boolean.FALSE);
            productCdk.setCdk(cdk);
            productCdk.insert();
        }
    }

    @Override
    public List<ProductCdkVO> getCdkList(Long productId) {
        return productCdkDao.getCdkListByProduct(productId);
    }

    @Override
    public Page<ProductCdkVO> getPageCdkList(Long productId, int pageNo, int pageSize) {
        return productCdkDao.getPageCdkList(productId, pageNo, pageSize);
    }

    /**
     * 生成CDK
     *
     * @param usableStockCount
     * @return
     */
    private HashSet<String> generateCDK(Integer usableStockCount) {

        HashSet<String> daoListByIsUse = productCdkDao.getListByIsUse();

        HashSet<String> cdks = new HashSet<>(usableStockCount);

        while (true) {
            String cdk = RandomStringUtils.randomAlphanumeric(16);
            //如果不包含 就是全新的
            if (!daoListByIsUse.contains(cdk)) {
                cdks.add(cdk);
            }

            if (cdks.size() == usableStockCount) {
                break;
            }
        }
        return cdks;
    }


    /**
     * 新增竞拍商品
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAuctionProduct(AddAuctionProductDTO request) {
        DigitalCollectionProductInfoAuctionDTO digitalCollectionProductInfoAuctionDTO = request.getDigitalCollectionProductInfoAuction();

        if (request.getCommodityType() != CommodityType.AUCTION_PRODUCT) {
            throw new GlobalRunTimeException("该类型无法创建商品");
        }
        if (digitalCollectionProductInfoAuctionDTO.getAuctionStartTime().after(digitalCollectionProductInfoAuctionDTO.getAuctionEndTime())) {
            throw new GlobalRunTimeException("开始时间不能在结束时间之后");
        }
        Date date = new Date();
        if (date.after(digitalCollectionProductInfoAuctionDTO.getAuctionStartTime())) {
            throw new GlobalRunTimeException("开始时间不能当前时间之前");
        }
        if (date.after(digitalCollectionProductInfoAuctionDTO.getAuctionEndTime())) {
            throw new GlobalRunTimeException("结束时间不能当前时间之前");
        }
        // 锁仓判定
        if (!request.lockedPositionDecide()) {
            throw new GlobalRunTimeException(ErrorCode.LOCKED_POSITION);
        }

        List<DigitalCollectionProductInfoAuctionConditionDTO> digitalCollectionProductInfoAuctionConditionList = request.getDigitalCollectionProductInfoAuctionConditionList();
        List<Integer> digitalCollectionProductInfoAuctionConsumptionIds = request.getDigitalCollectionProductInfoAuctionConsumptionIds();
        DigitalCollectionProductInfo productInfo = BeanUtil.toBean(request, DigitalCollectionProductInfo.class);

        ProductStock productStock = new ProductStock();
        productInfo.setStatus(false);
        productInfo.setIsEnable(false);
        productInfo.setIsSoldOut(false);
        productInfo.setIsRegisterTime(Boolean.FALSE);
        productInfo.setIsPriorityPurchase(Boolean.FALSE);//优先购
        productInfo.setIsRushBuy(Boolean.FALSE);//优先抢
        productInfo.setIsUpgrade(Boolean.FALSE);//升级藏品
        productInfo.setAppleProductId(AppleProductEnum.SEVENTY_THREE.getId());
        productInfo.setIsRegisterTime(Boolean.FALSE);
        switch (request.getTypeClassify()) {

            case COLLECTION:
                DigitalCollection digitalCollection = digitalCollectionDao.getById(productInfo.getRelationId());
                if (digitalCollection.getChainStatus() != CollectionChainStatusEnum.CHAIN_COMPLETED) {
                    throw new GlobalRunTimeException("该藏品未上链，不能创建商品");
                }
                if (request.getTypeClassify() == ClassifyType.COLLECTION) {
                    if (digitalCollectionProductInfoAuctionDTO.getAuctionNum() <= 0) {
                        throw new GlobalRunTimeException("商品数量不正确");
                    }
                }
                if (productInfo.getTypeClassify() == ClassifyType.COLLECTION) {
                    if (digitalCollectionProductInfoAuctionDTO.getAuctionNum() > digitalCollection.getUsableCount()) {
                        throw new GlobalRunTimeException("藏品库存不足");
                    }
                }
                //特权藏品校验是否设置权益
                if (digitalCollection.getIsPrivilege()) {
                    List<Privilege> list = privilegeService.getByCollectionId(digitalCollection.getId());
                    if (list.size() <= 0) {
                        throw new GlobalRunTimeException("特权藏品未设置权益");
                    }
                }
                CatenaInfo catenaInfo = (CatenaInfo) new CatenaInfo().selectById(productInfo.getCatenaId());
                if (ObjectUtil.isNotEmpty(catenaInfo)) {
                    productInfo.setCatenaName(catenaInfo.getName());
                }
                long snowflakeNextId = IdUtil.getSnowflakeNextId();
                productInfo.setDigitalCollectionProductInfoUuid("nft" + String.valueOf(snowflakeNextId));
                productInfo.setIsUpgrade(digitalCollection.getIsUpgrade());
                productInfo.setUserCreatorId(digitalCollection.getUserCreatorId());
                productInfo.setLevel(digitalCollection.getLevel().getCode());
                productInfo.setIsUpgrade(digitalCollection.getIsUpgrade());
                productInfo.setDaoLevel(digitalCollection.getDaoLevel());
                productInfo.setModelImg(digitalCollection.getModelImg());
                productInfo.setModelDistance(digitalCollection.getModelDistance());
                productInfo.setThreeModelId(digitalCollection.getThreeModelId());
                productInfo.setSkipUrl(digitalCollection.getSkipUrl());
                productInfo.setProductNum(digitalCollectionProductInfoAuctionDTO.getAuctionPrice());
                productInfo.setBeginTime(digitalCollectionProductInfoAuctionDTO.getAuctionStartTime());
                productInfo.setEndTime(digitalCollectionProductInfoAuctionDTO.getAuctionEndTime());
                productStock.setSellCount(0);
                productStock.setFrozenCount(0);
                productStock.setUsableCount(digitalCollectionProductInfoAuctionDTO.getAuctionNum());
                productStock.setSumCount(digitalCollectionProductInfoAuctionDTO.getAuctionNum());
                productStock.setStockType(StockType.COLLECTION);
                productStock.setRelationId(request.getRelationId());
                productStock.setVersion(0);
                break;
            case BLIND_BOX:
                BoxProduct boxProduct = boxProductService.getById(request.getRelationId());
                productInfo.setUserCreatorId(boxProduct.getUserCreatorId());
                productInfo.setAboutBox(boxProduct.getAboutBox());
                productInfo.setBoxDetailsPicture(boxProduct.getBoxDetailsPicture());
                productInfo.setProductPresentation(boxProduct.getProductPresentation());
                if (productInfo.getCommodityType() == CommodityType.PRODUCT) {
                    productInfo.setAppleProductId(AppleProductEnum.BLINDBOX.getId());
                }
                if (BooleanUtil.isFalse(boxProduct.getStatus())) {
                    throw new GlobalRunTimeException("·");
                }
                productStock.setStockType(StockType.BLIND_BOX);
                productStock.setSellCount(0);
                productStock.setFrozenCount(0);
                productStock.setUsableCount(boxProduct.getBoxCount());
                productStock.setRelationId(request.getRelationId());
                productStock.setSumCount(boxProduct.getBoxCount());
                productStock.setVersion(0);
                break;
        }
        productInfo.insert();
        digitalCollectionProductInfoAuctionDTO.setProductId(productInfo.getId());
        if (productInfo.getTypeClassify() == ClassifyType.COLLECTION) {
            digitalCollectionDao.uodateCollectionStock(productInfo.getRelationId(), productStock.getSumCount());
        }
        productStock.setProductId(productInfo.getId());
        productStock.insert();
        if (productInfo.getTypeClassify() == ClassifyType.BLIND_BOX) {
            boxItemDao.getBoxItem(productInfo.getRelationId()).forEach(boxItem -> {
                ProductStock productStockItem = new ProductStock();
                DigitalCollection boxDigital = digitalCollectionDao.getById(boxItem.getCollectionId());
                if (boxDigital.getUsableCount() < boxItem.getSumCount()) {
                    throw new GlobalRunTimeException("盲盒中的" + boxDigital.getFirstTitle() + "库存不足");
                }
                digitalCollectionDao.uodateCollectionStock(boxDigital.getId(), boxItem.getSumCount());
                productStockItem.setStockType(StockType.BOX_ITEM);
                productStockItem.setVersion(0);
                productStockItem.setProductId(productInfo.getId());
                productStockItem.setRelationId(productInfo.getRelationId());
                productStockItem.setStockType(StockType.BOX_ITEM);
                productStockItem.setItemId(boxItem.getId());
                productStockItem.setSumCount(boxItem.getSumCount());
                productStockItem.setUsableCount(boxItem.getSumCount());
                productStockItem.setFrozenCount(0);
                productStockItem.setSellCount(0);
                productStockItem.insert();
            });
        }

        DigitalCollectionProductInfoAuction digitalCollectionProductInfoAuction = BeanUtil.copyProperties(digitalCollectionProductInfoAuctionDTO, DigitalCollectionProductInfoAuction.class);
        digitalCollectionProductInfoAuction.setRuleImg(request.getRuleImg());
        digitalCollectionProductInfoAuctionDao.save(digitalCollectionProductInfoAuction);
        List<DigitalCollectionProductInfoAuctionCondition> digitalCollectionProductInfoAuctionConditions = BeanUtil.copyToList(digitalCollectionProductInfoAuctionConditionList, DigitalCollectionProductInfoAuctionCondition.class);
        for (DigitalCollectionProductInfoAuctionCondition digitalCollectionProductInfoAuctionCondition : digitalCollectionProductInfoAuctionConditions) {
            digitalCollectionProductInfoAuctionCondition.setProductId(productInfo.getId());
            digitalCollectionProductInfoAuctionConditionDao.save(digitalCollectionProductInfoAuctionCondition);
        }
        for (Integer digitalCollectionProductInfoAuctionConsumptionId : digitalCollectionProductInfoAuctionConsumptionIds) {

            DigitalCollection digitalCollection = digitalCollectionDao.getById(digitalCollectionProductInfoAuctionConsumptionId);
            DigitalCollectionProductInfoAuctionConsumptionCondition digitalCollectionProductInfoAuctionConsumptionCondition = new DigitalCollectionProductInfoAuctionConsumptionCondition();
            digitalCollectionProductInfoAuctionConsumptionCondition.setProductId(productInfo.getId());
            digitalCollectionProductInfoAuctionConsumptionCondition.setPledgeImage(digitalCollection.getCreationContent());
            digitalCollectionProductInfoAuctionConsumptionCondition.setFirstTitle(digitalCollection.getFirstTitle());
            digitalCollectionProductInfoAuctionConsumptionCondition.setRelationId(digitalCollection.getId());
            digitalCollectionProductInfoAuctionConsumptionCondition.setParticipationType(AcutionParticipationTypeEnum.HOLD_COLLECTION);
            digitalCollectionProductInfoAuctionConsumptionConditionDao.save(digitalCollectionProductInfoAuctionConsumptionCondition);
        }
    }

    /**
     * 修改竞拍商品
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyAuctionProduct(ModifyAuctionProductDTO request) {

        DigitalCollectionProductInfo digitalCollectionProductInfo = (DigitalCollectionProductInfo) new DigitalCollectionProductInfo().selectById(request.getProductId());
        if (ObjectUtil.isEmpty(digitalCollectionProductInfo)) {
            throw new GlobalRunTimeException(ErrorCode.PRODUCT_NOT_FOUND);
        }


        if (!digitalCollectionProductInfo.getIsSmeltingOnly().equals(request.getIsSmeltingOnly())) {
            throw new GlobalRunTimeException("仅熔炼选项不支持修改");
        }

        if (digitalCollectionProductInfo.getStatus()) {
            throw new GlobalRunTimeException("商品上架中不可做修改");
        }
        if (digitalCollectionProductInfo.getEndTime() != request.getEndTime() && DateTime.now().isAfter(digitalCollectionProductInfo.getEndTime())) {
            throw new GlobalRunTimeException("商品已过期，不能修改");
        }

        //判断是否有用户拍卖的数据
        Integer count = digitalCollectionProductInfoAuctionUserBiddingDao.countByProductId(request.getProductId());
        if (null != count && count > 0) {
            throw new GlobalRunTimeException("该商品有用户拍卖数据，不能修改");
        }

        // 锁仓判定
        if (!request.lockedPositionDecide()) {
            throw new GlobalRunTimeException(ErrorCode.LOCKED_POSITION);
        }
        ProductStock byProductId = productStockDao.getByProductId(request.getProductId());
        Integer usableCount = byProductId.getUsableCount();
        if (request.getDigitalCollectionProductInfoAuction().getAuctionNum() > usableCount) {
            throw new GlobalRunTimeException("标的物数量大于可用库存,请先增加库存");
        }
        DigitalCollectionProductInfoAuctionDTO digitalCollectionProductInfoAuction = request.getDigitalCollectionProductInfoAuction();
        Date date = new Date();
        if (date.after(digitalCollectionProductInfoAuction.getAuctionStartTime())) {
            throw new GlobalRunTimeException("开始时间不能当前时间之前");
        }
        if (date.after(digitalCollectionProductInfoAuction.getAuctionEndTime())) {
            throw new GlobalRunTimeException("结束时间不能当前时间之前");
        }
        if (digitalCollectionProductInfoAuction.getAuctionStartTime().after(digitalCollectionProductInfoAuction.getAuctionEndTime())) {
            throw new GlobalRunTimeException("开始时间不能在结束时间之后");
        }
        digitalCollectionProductInfo.setFirstTitle(request.getFirstTitle());
        digitalCollectionProductInfo.setProductNum(digitalCollectionProductInfoAuction.getAuctionPrice());
        digitalCollectionProductInfo.setBeginTime(digitalCollectionProductInfoAuction.getBeginTime());
        digitalCollectionProductInfo.setEndTime(digitalCollectionProductInfoAuction.getEndTime());
        digitalCollectionProductInfo.setPlatformShow(request.getPlatformShow());
        digitalCollectionProductInfo.setBrandShow(request.getBrandShow());
        digitalCollectionProductInfo.setFirmShow(request.getFirmShow());
        digitalCollectionProductInfo.setIsLockedPosition(request.getIsLockedPosition());
        digitalCollectionProductInfo.setLockedPositionType(request.getLockedPositionType());
        digitalCollectionProductInfo.setLockedPositionHour(request.getLockedPositionHour());
        digitalCollectionProductInfo.setLockedPositionTime(request.getLockedPositionTime());
        digitalCollectionProductInfo.updateById();
        DigitalCollectionProductInfoAuction byProductInfoAuction = digitalCollectionProductInfoAuctionDao.getByProductInfoAuction(request.getProductId());
        if (BeanUtil.isNotEmpty(byProductInfoAuction)) {
            BeanUtil.copyProperties(request.getDigitalCollectionProductInfoAuction(), byProductInfoAuction);
            byProductInfoAuction.setRuleImg(request.getRuleImg());

        }
        digitalCollectionProductInfoAuctionDao.updateByProductId(byProductInfoAuction);
        digitalCollectionProductInfoAuctionConditionDao.removeByProductId(request.getProductId());
        digitalCollectionProductInfoAuctionConsumptionConditionDao.removeByProductId(request.getProductId());

        List<DigitalCollectionProductInfoAuctionConditionDTO> digitalCollectionProductInfoAuctionConditionList = request.getDigitalCollectionProductInfoAuctionConditionList();
        List<DigitalCollectionProductInfoAuctionCondition> digitalCollectionProductInfoAuctionConditions = BeanUtil.copyToList(digitalCollectionProductInfoAuctionConditionList, DigitalCollectionProductInfoAuctionCondition.class);
        digitalCollectionProductInfoAuctionConditions.forEach(e -> e.setProductId(request.getProductId()));
        digitalCollectionProductInfoAuctionConditionDao.saveBatch(digitalCollectionProductInfoAuctionConditions);
        List<Integer> digitalCollectionProductInfoAuctionConsumptionIds = request.getDigitalCollectionProductInfoAuctionConsumptionIds();

        for (Integer digitalCollectionProductInfoAuctionConsumptionId : digitalCollectionProductInfoAuctionConsumptionIds) {

            DigitalCollection digitalCollection = digitalCollectionDao.getById(digitalCollectionProductInfoAuctionConsumptionId);
            DigitalCollectionProductInfoAuctionConsumptionCondition digitalCollectionProductInfoAuctionConsumptionCondition = new DigitalCollectionProductInfoAuctionConsumptionCondition();
            digitalCollectionProductInfoAuctionConsumptionCondition.setProductId(digitalCollectionProductInfo.getId());
            digitalCollectionProductInfoAuctionConsumptionCondition.setPledgeImage(digitalCollection.getCreationContent());
            digitalCollectionProductInfoAuctionConsumptionCondition.setFirstTitle(digitalCollection.getFirstTitle());
            digitalCollectionProductInfoAuctionConsumptionCondition.setRelationId(digitalCollection.getId());
            digitalCollectionProductInfoAuctionConsumptionCondition.setParticipationType(AcutionParticipationTypeEnum.HOLD_COLLECTION);
            digitalCollectionProductInfoAuctionConsumptionConditionDao.save(digitalCollectionProductInfoAuctionConsumptionCondition);
        }
    }

    /**
     * 根据id查询竞拍商品 （详情）
     * @param id
     * @return
     */
    @Override
    public AuctionProductAdminVO getAuctionProductById(Long id) {
        DigitalCollectionProductInfo digitalCollectionProductInfo = (DigitalCollectionProductInfo) new DigitalCollectionProductInfo().selectById(id);
        AuctionProductAdminVO auctionProductAdminVO = BeanUtil.toBean(digitalCollectionProductInfo, AuctionProductAdminVO.class);
        auctionProductAdminVO.setTypeClassify(digitalCollectionProductInfo.getTypeClassify());
        // 根据判定获取时间判断.
        DigitalCollectionProductInfoAuction byProductInfoAuction = digitalCollectionProductInfoAuctionDao.getByProductInfoAuction(id);
        auctionProductAdminVO.setRuleImg(byProductInfoAuction.getRuleImg());
        if (BeanUtil.isEmpty(byProductInfoAuction)) {
            throw new GlobalRunTimeException("该任务数据异常,请联系管理人员");
        }
        auctionProductAdminVO.setDigitalCollectionProductInfoAuction(byProductInfoAuction);

        List<DigitalCollectionProductInfoAuctionCondition> digitalCollectionProductInfoAuctionConditionList = digitalCollectionProductInfoAuctionConditionDao.getDigitalCollectionProductInfoAuctionConditionByProductId(id);
        auctionProductAdminVO.setDigitalCollectionProductInfoAuctionConditionList(digitalCollectionProductInfoAuctionConditionList);

        List<DigitalCollectionProductInfoAuctionConsumptionCondition> digitalCollectionProductInfoAuctionConsumptionConditionList = digitalCollectionProductInfoAuctionConsumptionConditionDao.getDigitalCollectionProductInfoAuctionConsumptionConditionByProductId(id);
        auctionProductAdminVO.setDigitalCollectionProductInfoAuctionConsumptionList(digitalCollectionProductInfoAuctionConsumptionConditionList);
        return auctionProductAdminVO;
    }

}
